package com.chiyou.common.utils;
import java.util.logging.Logger;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import redis.clients.jedis.JedisPool;

/**
 * 利用单例模式实现redis的连接池
 * @author 陈嘉瑛
 * @version 2015-12-03
 *
 */
public class JdiresPool {
	//单机连接池
	private static JedisPool jedisPool ;
	private static Log logger = LogFactory.getLog(JdiresPool.class);

	private JdiresPool(){}

	static{
		initJpool();
	}
	
	/**
	 * 初始化连接池
	 */
	private static void initJpool(){
		try{
			logger.debug("====1redis ip:" + RedisConfigUtil.REDIS_IP);
			logger.debug("====1redis port:" + RedisConfigUtil.REDIS_PORT);
			GenericObjectPoolConfig config = new GenericObjectPoolConfig();
			config.setMaxIdle(RedisConfigUtil.MAXIDL);
			config.setMaxWaitMillis(RedisConfigUtil.MAXWAIT);
			config.setTestOnBorrow(false);
			if(RedisConfigUtil.REDIS_PWD == null || RedisConfigUtil.REDIS_PWD.trim().equals(""))
				jedisPool = new JedisPool(config, RedisConfigUtil.REDIS_IP, RedisConfigUtil.REDIS_PORT);
			else
				//如果有设置密码要输入密码校验
				jedisPool = new JedisPool(config, RedisConfigUtil.REDIS_IP, RedisConfigUtil.REDIS_PORT,0,RedisConfigUtil.REDIS_PWD);
			logger.debug("====redis ip:" + RedisConfigUtil.REDIS_IP);
			logger.debug("====redis port:" + RedisConfigUtil.REDIS_PORT);
		}catch (Exception e) {
			System.out.println("初始化redis连接池异常!");
			logger.error("初始化redis连接池异常!");
		}
	}

	/**
	 * 获取redis单机连接池
	 */
	public static JedisPool getJdisPool(){
		if(jedisPool == null) initJpool();
		return jedisPool;
	}

	/**
	 * 失效redis单机连接池
	 */
	public static void destroyJpool(){
		if(jedisPool != null) jedisPool.destroy();
	}
}
